/**
    JavaScript module for KB debug page.
    TODO: Add handler for ajax errors
*/
DEBUGKB = function() {
    function load_lookup_table() {
        var tablename = $("#tablename_select option:selected").text();
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/load_table',
            data:{'tablename':tablename},
            success:function(result) {
                display_data_table(result.data, '#lookup_table_display', 'lookup_table_table');
            }
        });
        return false;
    }
    
    function reconstitute_object() {
        var object = $('#reconstitute').val();
        $.ajax({
            type:'POST',
            datatype:'json',
            url:'/reconstitute',
            data:{'object':object},
            success:function(result) {
                display_data_table(result.data, '#reconstitute_results', 'reconstitute_table');
            }
        });
        return false;
    }
    
    function display_data_table(data_list, container, table) {
        $(container).show();
        var tbody = $('<tbody>').attr('id',table);
        $.each(data_list, function(index,item) {
          var tr = $('<tr>')
          $('<td>').text(item.id).appendTo(tr);
          var tmp_val = null;
          if ($.isArray(item.value)) {
              tmp_val = item.value.join(', ');
          } else {
              tmp_val = item.value;
          }
          
          $('<td>').text(tmp_val).appendTo(tr);
          tr.appendTo(tbody);
        });
        var tid = '#' + table;
        $(tid).replaceWith(tbody);
    }
        
    return {
        init : function(conf) {
            var config = conf || {};
            /** configure visibility */
            $('#lookup_table_display').hide();
            $('#reconstitute_results').hide();
            /** hook up events */
            $('#tablename_select').change(function() { load_lookup_table(); });
            $('#do_reconstitute').click(function() { reconstitute_object(); });
        }
    }
}();
    
    